package org.irri.smta.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import org.irri.smta.report.Smta;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class SmtaXmlUtils {
	
	public static Smta deserializeXmlFileToSmta(String xmlFilepath) throws IOException {
		File xmlFile = new File(xmlFilepath);
		if (xmlFile != null && xmlFile.exists() && xmlFile.isFile() && xmlFile.canRead()) {
			return deserializeXmlFileToSmta(xmlFile);
		}
		return null;
	}
	
	public static Smta deserializeXmlFileToSmta(File xmlFile) throws IOException {
		// Instantiate XStream Object
		XStream xstream = new XStream(new DomDriver());

		// Set Person class into XStream alias
		xstream.alias("smta", Smta.class);
		xstream.alias("provider", Smta.Provider.class);
		xstream.alias("recipient", Smta.Recipient.class);
		xstream.alias("annex1", Smta.Annex1.class);
		xstream.alias("material", Smta.Annex1.Material.class);
		xstream.alias("document", Smta.Document.class);
		xstream.addImplicitCollection(Smta.Annex1.class, "material");

		StringBuffer contents = new StringBuffer();
		// Set BufferReader to read from XML file
		BufferedReader br = new BufferedReader(new FileReader(xmlFile));

		String str = null;
		while ((str = br.readLine()) != null) {
			contents.append(str);
		}
		br.close();

		// Put all the contents from contents to String variable content
		String content = contents.toString();
		// Convert XML content to Smta object
		Smta smta = (Smta) xstream.fromXML(content);
		
		return smta;
	}
	
}